import { UsageManager } from '../../utils/usage';

Page({
  data: {
    imageUrl: '',
    remainingUsage: 0
  },

  onLoad(options) {
    if (options.imageUrl) {
      this.setData({
        imageUrl: decodeURIComponent(options.imageUrl)
      });
    }
    this.setData({ 
      remainingUsage: UsageManager.getRemainingUsage()
    });
  },

  handleContinue() {
    if (this.data.remainingUsage <= 0) {
      wx.showToast({
        title: '今日生成次数已用完',
        icon: 'none'
      });
      return;
    }
    wx.redirectTo({
      url: '/pages/create/create'
    });
  },

  handleDownload() {
    wx.showLoading({
      title: '下载中...'
    });

    wx.downloadFile({
      url: this.data.imageUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.hideLoading();
              wx.showToast({
                title: '保存成功',
                icon: 'success'
              });
            },
            fail: (error) => {
              wx.hideLoading();
              if (error.errMsg.includes('auth deny')) {
                wx.showModal({
                  title: '提示',
                  content: '需要您授权保存到相册',
                  success: (res) => {
                    if (res.confirm) {
                      wx.openSetting();
                    }
                  }
                });
              } else {
                wx.showToast({
                  title: '保存失败',
                  icon: 'error'
                });
              }
            }
          });
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '下载失败',
            icon: 'error'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '下载失败',
          icon: 'error'
        });
      }
    });
  }
}); 